package dao

import (
	"go_my_framework/app/core/db"
	"go_my_framework/app/model"
	"time"
)

type CategoryDao interface {
	FindRow(id int) model.Category
	FindRowByName(name string) (model.Category, error)
	GetList(page int, limit int, name string) ([]model.Category, int64, error)
	Create(name string, pid int, sort int) error
	Update(id int, name string, pid int, sort int) error
	Del(id int) error
}

func NewCategoryDaoImpl() CategoryDao {
	return new(CategoryDaoImpl)
}

type CategoryDaoImpl struct {

}

func (p *CategoryDaoImpl) FindRow(id int) (data model.Category) {
	db.Instance().
		Model(model.Category{}).
		Where("id = ?", id).
		First(&data)
	return data
}

func (p *CategoryDaoImpl) FindRowByName(name string) (data model.Category, err error) {
	err = db.Instance().
		Model(model.Category{}).
		Where("name = ?", name).
		First(&data).
		Error
	return data, err
}

func (a *CategoryDaoImpl) GetList(page int, limit int, name string) (data []model.Category, count int64, err error) {
	obj := db.Instance().Model(model.Category{})
	if name != "" {
		obj = obj.Where("name = ?", name)
	}
	obj = obj.Count(&count)
	err = obj.Limit(limit).Offset((page - 1) * limit).Find(&data).Error
	return
}

func (a *CategoryDaoImpl) Create(name string, pid int, sort int) error {
	dateTime := time.Now().Format("2006-01-02 15:04:05")
	data := model.Category{
		Name:      name,
		Pid:       pid,
		Sort:      sort,
		CreatedAt: dateTime,
		UpdatedAt: dateTime,
	}
	return db.Instance().Model(&model.Category{}).Create(&data).Error
}

func (a *CategoryDaoImpl) Update(id int, name string, pid int, sort int) error {
	data := model.Category{
		Name:     name,
		Pid:      pid,
		Sort:     sort,
	}
	return db.Instance().Model(model.Category{}).Where("id = ?", id).Updates(data).Error
}

func (a *CategoryDaoImpl) Del(id int) error {
	return db.Instance().Where("id = ?", id).Delete(model.Category{}).Error
}